<?php

/* USER_FILE_NAME has this structure:
 * 
 * {
 *   "username': md5("password"),
 *   "anotherUsername': md5("password")
 * }
 *
 *
 * SAVE_FILE_NAME has this structure:
 *
 * {
 *   "username": {
 *     "sectors": {
 *       "name": "data"
 *     },
 *     "pricelists": {
 *       "name": "data"
 *     }
 *   }
 * }
 *
 */

require_once('../config.php');
require_once('./messages.php');

function _RawSend($data)
{
  die(json_encode($data));
}

function Send($data = array())
{
  $data['Status'] = STATUS_OK;
  _RawSend($data);
}

function SendLoginFailed($data = array())
{
  $data['Status'] = STATUS_LOGIN_FAILED;
  _RawSend($data);
}

function SendCorrupt($data = array())
{
  $data['Status'] = STATUS_CORRUPT;
  _RawSend($data);
}

function SendError($error, $data = array())
{
  $data['Status'] = STATUS_ERROR;
  $data['Error'] = $error;
  _RawSend($data);
}

$cache = array();

function ReadJSONFile($name)
{
  global $cache;

  if(array_key_exists($name, $cache))
  {
    return $cache[$name];
  }
  else
  {
    if(!file_exists($name))
      WriteJSONFile($name, array());

    $json = json_decode(str_replace('<?php ', '', str_replace(' ?>', '', file_get_contents($name))), true);
    $cache[$name] = $json;
    return $json;
  }
}

function WriteJSONFile($name, $json)
{
  global $cache;

  $cache[$name] = $json;
  file_put_contents($name, '<?php '.json_encode($json).' ?>');
}

function VerifyUser($username, $password)
{
  // First, load the users.
  $users = ReadJSONFile(USER_FILE_NAME);

  if(!isset($users[$username]))
  {
    throw new Exception('Unknown User');
  }

  else
  {
    $storedPassword = $users[$username];

    if($storedPassword != $password) // Check password
      throw new Exception('Incorrect Password');
  }
}

function AddUser($username, $password)
{
  $users = ReadJSONFile(USER_FILE_NAME);

  if(isset($users[$username]))
    throw new Exception('Username Not Available');

  $saves = ReadJSONFile(SAVE_FILE_NAME);

  $users[$username] = $password;
  $saves[$username] = array('sectors' => array(), 'pricelists' => array());

  WriteJSONFile(USER_FILE_NAME, $users);
  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function DeleteUser($username)
{
  $users = ReadJSONFile(USER_FILE_NAME);
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  unset($users[$username]);
  unset($saves[$username]);

  WriteJSONFile(USER_FILE_NAME, $users);
  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function GetSectors($username)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  return $saves[$username]['sectors'];
}

function GetPricelists($username)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  return $saves[$username]['pricelists'];
}

function GetSector($username, $name)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  if(!isset($saves[$username]['sectors'][$name]))
    throw new Exception('Does Not Exist');

  return $saves[$username]['sectors'][$name];
}

function GetPricelist($username, $name)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  if(!isset($saves[$username]['pricelists'][$name]))
    throw new Exception('Does Not Exist');

  return $saves[$username]['pricelists'][$name];
}

function AddSector($username, $name, $data)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);
  $sectors = &$saves[$username]['sectors'];

  if(isset($sectors[$name]))
    throw new Exception('Sector Already Exists');

  if(count($sectors) >= MAX_SAVED_SECTORS)
    throw new Exception('Exceeded Quota');

  $sectors[$name] = $data;

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function AddPricelist($username, $name, $data)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);
  $pricelists = &$saves[$username]['pricelists'];

  if(isset($pricelists[$name]))
    throw new Exception('Pricelist Already Exists');

  if(count($pricelists) >= MAX_SAVED_PRICELISTS)
    throw new Exception('Exceeded Quota');

  $pricelists[$name] = $data;

  WriteJSONFile(SAVE_FILE_NAME, $saves);

  return true;
}

function UpdateSector($username, $name, $data)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);
  $sectors = &$saves[$username]['sectors'];

  if(!isset($sectors[$name]))
    throw new Exception('Does Not Exist');

  $sectors[$name] = $data;

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function UpdatePricelist($username, $name, $data)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);
  $pricelists = &$saves[$username]['pricelists'];

  if(!isset($pricelists[$name]))
    throw new Exception('Does Not Exist');

  $pricelists[$name] = $data;

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function DeleteSector($username, $name)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  unset($saves[$username]['sectors'][$name]);

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function DeletePricelist($username, $name)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  unset($saves[$username]['pricelists'][$name]);

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function RenameSector($username, $oldName, $newName)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  $sectors = &$saves[$username]['sectors'];

  if(!isset($sectors[$oldName]))
    throw new Exception('Does Not Exist');

  $sectors[$newName] = $sectors[$oldName];
  unset($sectors[$oldName]);

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function RenamePricelist($username, $oldName, $newName)
{
  $saves = ReadJSONFile(SAVE_FILE_NAME);

  $pricelists = &$saves[$username]['pricelists'];

  if(!isset($pricelists[$oldName]))
    throw new Exception('Does Not Exist');

  $pricelists[$newName] = $pricelists[$oldName];
  unset($pricelists[$oldName]);

  WriteJSONFile(SAVE_FILE_NAME, $saves);
}

function GetSectorCode($name)
{
  $sectors = ReadJSONFile('./sectors.js');

  if(!isset($sectors[$name]))
    throw new Exception('Does Not Exist');

  return $sectors[$name];
}

function GetName($data)
{
  preg_match('/"name":"([a-zA-Z0-9 -]*)"/', $data, $matches);
  return $matches[1];
}

function ExtractMap($code)
{
  preg_match('/"map":"([a-zA-Z0-9 -]*)"/', $code, $matches);
  return $matches[1];
}

?>